@extends('layouts.admin')
@section('style')
    <style type="text/css">
        .box_form .layui-input-inline {
            width: 400px;
            min-width: 200px;
        }

        .layui-form-select dl {
            z-index: 99999;
        }
    </style>
@endsection
@section('content')
    <div style="padding:5px;">
        <div class="admin_base">
            <div class="admin_module clearfix">
                <blockquote style="margin-top:5px;font-size:16px" class="layui-elem-quote">
                    流程：下载模板 》 填写模板 》 导入表格 》确定保存 <span style="color:red">（建议每次导入不超过500条）</span>
                </blockquote>
                <div id="list_search" style="width:100%" class="clearfix">
                    <form action="{{ url('order/import') }}" id="VoForm" class="layui-form layui-form-pane"
                          novalidate="1">
                        <div clss="layui-inline">
                            <div class="layui-form-item">
                                <div class="layui-input-inline">
                                    <select name="shop_id" id="shop_id" style="width:auto" lay-filter="shop_id">
                                        <option value="">选择店铺</option>
                                        @foreach($shops as $shop)
                                            <option value="{{ $shop->id }}">{{ $shop->title }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-inline">
                                    <input type="file" style="display: none" id="file"
                                           data-url="{{ url('order/import') }}"/>
                                    <button class="layui-btn" lay-submit lay-filter="btn_import">导入</button>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-inline">
                                    <button class="layui-btn layui-btn-normal" style="float:right;display:none"
                                            id="btn_save" lay-submit lay-filter="btn_save">确定保存
                                    </button>
                                </div>
                            </div>
                            <div class="layui-form-item" style="float:right;">
                                <div class="layui-input-inline">
                                    <a class="layui-btn layui-btn-warm"
                                       href="{{ asset('files/template/template.xlsx') }}">下载模板</a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="box_list">
                <div class="box_content">
                    <form method="post" action="" id="list_form" class="layui-form" novalidate="1">
                        {{ csrf_field() }}
                        <table class="layui-table list" lay-data="{height:455, page:true, id:'dataList'}" lay-skin="row"
                               lay-even="true" lay-filter="dataList" id="data-list">
                            <colgroup>
                                <col width="59"/>
                            </colgroup>
                            <thead>
                            <tr>
                                <th lay-data="{field:'order_time', width:150}">订单时间</th>
                                <th lay-data="{field:'order_no', width:100}">订单编号</th>
                                <th lay-data="{field:'account_no', width:100}">买家账号</th>
                                <th lay-data="{field:'item_id', width:100}">宝贝ID</th>
                                <th lay-data="{field:'item_title', width:200}">宝贝标题</th>
                                <th lay-data="{field:'price', width:60}">价格</th>
                                <th lay-data="{field:'commission', width:60}">佣金</th>
                                <th lay-data="{field:'user_id', width:100}">操作员</th>
                                <th lay-data="{field:'comm'}">备注</th>
                            </tr>
                            </thead>
                        </table>
                    </form>
                </div>
            </div>
        </div>
        <div class="admin_bottom"></div>
    </div>
@endsection
@section('script')
    <script type="text/javascript" src="{{ asset('files/ueditor/ueditor.config.js') }}"></script>
    <script type="text/javascript" src="{{ asset('files/ueditor/ueditor.all.js') }}"></script>
    <script type="text/javascript" src="{{ asset('files/ueditor/lang/zh-cn/zh-cn.js') }}"></script>
    <script type="text/javascript">
        function showError(layer,datas){
            var _content = "";
            for(var i=0;i<datas.length;i++){
                _content += datas[i]+"\r\n";
            }
            var _html = '<textarea style="width:80%;height:80%;padding:5%;">'+_content+'</textarea>'
            layer.open({
                type:1,
                content:_html,
                area:['600px','500px'],
                title:false
            })
        }
        layui.use(['form', 'laydate', 'element', 'layer', 'utils', 'formField', 'table'], function () {
            var form = layui.form;
            var element = layui.element;
            var URL = layui.utils.URL;
            var errorTip = layui.utils.errorTip;
            var $ = layui.$;
            var layer = layui.layer;
            var table = layui.table;
            var _import_data = {};
            form.on('submit(btn_import)', function (data) {
                var _shop_id = $("#shop_id").val();
                if (_shop_id == '') {
                    layer.msg('请选择选择店铺', {icon: 5, time: 1000});
                    return false;
                }
                $("#file").click();
                return false;
            })
            var tableObj = table.init('dataList', {
                height: 315 //设置高度
                , limit: 10 //注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
                //支持所有基础参数
            });
            var _loadlay_id = null;
            $("#file").change(function () {
                var files = $(this)[0];
                var fileName = $(this).val();
                var seat = fileName.lastIndexOf(".");
                //返回位于String对象中指定位置的子字符串并转换为小写.
                var extension = fileName.substring(seat).toLowerCase();
                var allowed = [".xls", ".xlsx"];
                var _allow = false;
                for (var i = 0; i < allowed.length; i++) {
                    if (allowed[i] == extension) {
                        _allow = true;
                    }
                }
                if (!_allow) {
                    layer.msg("请上传正确的表格文件", {icon: 5, time: 1000});
                    return false;
                }
                var _post_url = $(this).data('url');
                var formData = new FormData();
                formData.append('file', files.files[0]);
                $.ajax({
                    url: _post_url,
                    type: 'POST',
                    cache: false,
                    data: formData,
                    timeout: 5000,
                    //必须false才会避开jQuery对 formdata 的默认处理
                    // XMLHttpRequest会对 formdata 进行正确的处理
                    processData: false,
                    //必须false才会自动加上正确的Content-Type
                    contentType: false,
                    xhrFields: {
                        withCredentials: true
                    },
                    beforeSend:function(){
                        _loadlay_id =layer.load();
                    },
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('导入成功', {icon: 6, time: 2000}, function () {
                                var _datas = res.data;
                                if (_datas.length > 0) {
                                    table.reload('dataList', {
                                        data: _datas
                                    })
                                    _import_data = _datas;
                                    $("#btn_save").show();
                                }
                            })
                        } else {
                            layer.msg(res.msg, {icon: 5, time: 2000}, function () {
                                 document.location.reload();
                            })
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    },
                    complete:function(){
                        layer.close(_loadlay_id);
                    }
                });
            });
            form.on('submit(btn_save)', function (data) {
                var url = $(data.form).prop('action');
                var _shop_id = $("#shop_id").val();
                var data = {submit: 1, data: _import_data,'shop_id':_shop_id};
                var Layer = parent.layer;
                Layer.confirm('确定要保存这些订单数据吗', {
                    title: '确认提示',
                    btn: ['立即保存', '再看看'],
                    yes: function (index) {
                        URL.post(url, data, {
                            dataType: 'json',
                            beforeSend:function(){
                                _loadlay_id =Layer.load();
                            },
                            success: function (res) {
                                if (res.code == 1) {
                                    if (res.data.error > 0) {
                                        Layer.alert(res.message, {icon: 0}, function (index) {
                                            Layer.close(index)
                                            showError(Layer,res.data.errors);
                                        }
                                       )
                                        document.location.reload();
                                    } else {
                                        Layer.msg(res.message, {icon: 6, times: 2000}, function () {
                                            if (res.data.error > 0) {
                                                document.location.reload();
                                            }
                                        })
                                    }
                                } else {
                                    layer.msg(res.message, {icon: 5, times: 2000});
                                }
                            },
                            complete:function(){
                                Layer.close(_loadlay_id);
                            }
                        })
                        parent.layer.close(index);
                    }
                })

                return false;
            })
        });
    </script>
@endsection